/**
 * 项目设置 编辑页
 *
 * 作者 ganjun
 * 日期 2024-11-12 10:58:48
 */
layui.use(['jquery', 'febs', 'form', 'formSelects', 'laydate', 'fileUpload', 'validate'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        formSelects = layui.formSelects,
        laydate = layui.laydate,
        $view = $('#sypqProject-edit'),
        $auditorid = $view.find('#auditorid'),
        $custCode = $view.find('#custCode'),
        $contact = $view.find('#contact'),
        $projectCode = $view.find('#projectCode'),
        $telephone = $view.find('#telephone'),
        validate = layui.validate;
  //  renderDate('#expectStartdate', 'yyyy-MM-dd HH:mm');
 //   renderDate('#expectEnddate', 'yyyy-MM-dd HH:mm');
    renderDate('#planStartdate', 'yyyy-MM-dd HH:mm');
    renderDate('#planEnddate', 'yyyy-MM-dd HH:mm');
    renderDate('#actualStartdate', 'yyyy-MM-dd HH:mm');
    renderDate('#actualEnddate', 'yyyy-MM-dd HH:mm');
    formSelects.render();
    formSelects.config('managerids', {
        searchUrl: ctx + 'sypqProject/getUserList',
        data: {},
        response: {
            statusCode: 200
        },
        beforeSuccess: function (id, url, searchVal, result) {
            var data = result.data;
            var tranData = [];
            for (var i = 0; i < data.length; i++) {
                tranData.push({
                    name: data[i].name,
                    value: data[i].code
                })
            }
            result.data = tranData;
            return result;
        },
        success: function () {
            formSelects.value('managerids',
                sypqProjectData.managerids == null ? [] : sypqProjectData.managerids.split(','));
        },
        error: function (id, url, searchVal, err) {
            console.error(err);
            febs.alert.error('获取角色列表失败');
        }
    });


    initDictSelect();
    form.verify(validate);
    form.render();
    initFormValue();

    function initDictSelect() {
        febs.initSelectByData($auditorid, userListData, sypqProjectData.auditorid, "");
        initCustomerOptions($custCode, customerListData, sypqProjectData.custCode, "");
        if (sypqProjectData.createdTime != null) {
            $projectCode.attr("readonly", true);
        }

    }

    function renderDate(element, format) {
        laydate.render({
            elem: element,
            type: 'datetime',
            format: format,
            btns: ['now', 'confirm'],
            trigger: 'click',
            isInitValue: true
        });
    }

    function initFormValue() {
        if (sypqProjectData) {
            form.val("sypqProject-edit-form", {
                "projectCode": sypqProjectData.projectCode,
                "projectName": sypqProjectData.projectName,
                "managerids": sypqProjectData.managerids,
                "auditorid": sypqProjectData.auditorid,
                "custCode": sypqProjectData.custCode,
                "contact": sypqProjectData.contact,
                "telephone": sypqProjectData.telephone,
                "status": sypqProjectData.status,
                "testDemand": sypqProjectData.testDemand,
                "expectStartdate": sypqProjectData.expectStartdate,
                "expectEnddate": sypqProjectData.expectEnddate,
                "planStartdate": sypqProjectData.planStartdate,
                "planEnddate": sypqProjectData.planEnddate,
                "actualStartdate": sypqProjectData.actualStartdate,
                "actualEnddate": sypqProjectData.actualEnddate,
                "createdTime": sypqProjectData.createdTime,
                "deletedFlg": sypqProjectData.deletedFlg,
                "approveStatus": sypqProjectData.approveStatus,
            });
        }
    }


    function initCustomerOptions(element, data, defaultValue, callBack) {
        $(element).empty()
        $(element).append(`<option value="">请选择</option>`)
        if (data != null && data.length > 0) {
            data.forEach(item => {
                if (defaultValue == item.custCode) {
                    element.append(`<option value="${item.custCode}"  selected>${item.custName}</option>`)
                } else {
                    element.append(`<option value="${item.custCode}" >${item.custName}</option>`)
                }
            })
        }
        if (typeof (callBack) === "function") {
            callBack(result);
        }
        layui.form.render('select');
    }


    form.on('submit(sypqProject-edit-form-save)', function (data) {
        var selectValue = formSelects.value('managerids', 'valStr');
        data.field.managerids = selectValue;
        addOrUpdate(data.field);

         return false;
    });


    form.on('submit(sypqProject-edit-form-submit)', function (data) {
        var selectValue = formSelects.value('managerids', 'valStr');
        data.field.managerids = selectValue;
        commit(data.field);
        return false;
    });


    form.on('select(custCode)', function (data) {
        if (customerListData != null && customerListData.length > 0) {
            customerListData.forEach(item => {
                if (item.custCode == data.value) {
                    $contact.val(item.contact);
                    $telephone.val(item.telephone);
                    form.render();

                }
            })
        }
    });


    function addOrUpdate(data) {
        febs.modal.confirm("保存提示！", "是否保存？", function (index) {
            var data1 = {};
            data1.sypqProject = data;
            data1.managerids = data.managerids;
            data1.type=typeData;
            data1.oldcode=oldcode;
            if (data.createdTime != "") {
                febs.postArray(ctx + 'sypqProject/update/' , data1, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    var currentUrl = window.location.hash.replace('#', '');
                    febs.view.tab.del(currentUrl);
                    febs.view.tab.change("/sypqProject");
                    $('#febs-sypqProject').find('#query').trigger('click');

                });
            } else {
                //项目名称做唯一性校验
                var   checkResult=getData(ctx + 'sypqProject/check',{projectCode:data.projectCode,projectName:data.projectName });
                if(checkResult.length>0){
                    febs.alert.warn(checkResult);
                    return ;
                }
                febs.postArray(ctx + 'sypqProject/', data1, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    var currentUrl = window.location.hash.replace('#', '');
                    febs.view.tab.del(currentUrl);
                    febs.view.tab.change("/sypqProject");
                    $('#febs-sypqProject').find('#query').trigger('click');

                });
            }
          })
    }

    function getData(url, condition) {
        var result;
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                console.log(data);
                result = data.data ;
            }
           });
        return result;
    }

    laydate.render({
        elem: '#ID-laydate-range',
        type:'datetime',
        format: 'yyyy-MM-dd HH:mm',
        btns: ['now', 'confirm'],
        trigger: 'click',
        isInitValue: true,
        range: ['#expectStartdate', '#expectEnddate']
    });

    function commit(data) {
        febs.modal.confirm("提交提示！", "是否提交？", function (index) {
            var data1 = {};
            data1.sypqProject = data;
            data1.managerids = data.managerids;
            data1.type=typeData;
            data1.oldcode=oldcode;
            if (data.createdTime == "") {
                var checkResult = getData(ctx + 'sypqProject/check', {
                    projectCode: data.projectCode,
                    projectName: data.projectName
                });
                if (checkResult.length > 0) {
                    febs.alert.warn(checkResult);
                    return;
                }
            }

            febs.postArray(ctx + 'sypqProject/commit/', data1, function () {
                layer.closeAll();
                febs.alert.success('提交成功');
                var currentUrl = window.location.hash.replace('#', '');
                febs.view.tab.del(currentUrl);
                febs.view.tab.change("/sypqProject");
                $('#febs-sypqProject').find('#query').trigger('click');
            });
        })
    }

});